package com.zjl.filter;

import com.alibaba.fastjson.JSON;
import com.zjl.common.BaseContext;
import com.zjl.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  检查用户是否完成登录
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
//urlPatterns:拦截路径，“/*"代表都拦截
public class LoginCheckFilter implements Filter {
//    路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        对servletRequest、servletResponse进行强转
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
//        1.获取本次请求uri
        String requestURI = request.getRequestURI();

        log.info("拦截到请求：{}",requestURI);

//        不需要处理的路径
        String[] notProcessedUrls=new String[]{
//                登录、退出、静态资源的请求，无需检查登录状态
                "/employee/login",
                //"/employee/page",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",//移动端登录
                "/user/sendMsg",//移动端发送短信

        };


//        2.判断本次请求是否需要检查登录状态
        boolean check = check(requestURI, notProcessedUrls);
        log.info("check:{}",check);

//        3.若该请求不需要判断登录状态，直接放行
        if(check){
//            放行操作
            log.info("本次请求{},无需处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //4-1.若需要判断登录状态,若已经登录，直接放行
            //从session中获取用户id,id不为空，表示已登录，可放行
        Long empId = (Long)request.getSession().getAttribute("employee");
        log.info("empid:{}",empId);
        if(empId!=null){
            log.info("已登录，用户id：{}",empId);

            BaseContext.setCurrent(empId);

            filterChain.doFilter(request,response);
            return;
        }

        //4-2.判断客户端登录状态,若已经登录，直接放行
            //从session中获取用户id,id不为空，表示已登录，可放行
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，用户id为:{}",request.getSession().getAttribute("user"));
            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrent(userId);

            filterChain.doFilter(request,response);
            return;
        }


        log.info("用户未登录");
//        5.若未登录，返回未登录结果，通过输出流向客户端传递数据
//        由于拦截器返回类型为void，所以这里无法正常使用return返回数据给服务器端，这里需要通过输出流来返回数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }


    /**
     * 路径匹配，检查当前uri是否需要放行
     * @param requestURI
     * @param notProcessedUrls
     * @return true:当前请求无需处理；
     *         false：需要判断该请求当前的登录状态
     */
    public boolean check(String requestURI,String[] notProcessedUrls){
        for (String url : notProcessedUrls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
